package memberrewards.service;

import hackathon1212.ServletPojoAdapter;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
import memberrewards.delegate.RewardsDelegate;
import memberrewards.dtos.AccountDetailDTO;
import memberrewards.dtos.CatalogItemDTO;

public class RedeemCatalogItem extends ServletPojoAdapter {
	private static final long serialVersionUID = 8166717310334174053L;

	protected Map<String,Object> getBusinessMethod(Map<String, String[]> params){
		//Query Params
		final String pan =params.get("pan")!=null? params.get("pan")[0]:null;
		final String itemId = params.get("citemid") != null ? params.get("citemid")[0] : null;
		
		//Default response
		final Map<String,Object> ret = new HashMap<String, Object>();
		ret.put("status", "Card Not Found");
		//get the account details
		final AccountDetailDTO accountDetail = RewardsDelegate.getAccountDetail(pan);		
		final CatalogItemDTO catalogItem=RewardsDelegate.getCatalogItem(itemId);
		//Check card is valid
		if (accountDetail!=null) {	
			if(catalogItem!=null){
				if(catalogItem.getTierList().contains(accountDetail.getTier())){
					final BigInteger pointsBalance = new BigInteger(accountDetail.getPointBalance());
					final BigInteger pointsToRedeem= new BigInteger(String.valueOf(catalogItem.getPointCost()));
					if(pointsToRedeem.compareTo(pointsBalance) == -1 || pointsToRedeem.compareTo(pointsBalance) == 0){
						final BigInteger newPointsBalance=pointsBalance.subtract(pointsToRedeem);
						accountDetail.setPointBalance(newPointsBalance.toString());
						boolean status=RewardsDelegate.updateAccountDetail(accountDetail);
						System.out.println(getClass().getName()+" UpdateStatus ::"+status);
						ret.put("balance", newPointsBalance);
						ret.put("status", status ? "Success" : "Failed to update Account Details");
					}
					else{
						ret.put("status", "Insufficient Points");
					}
				}
				else{
					//Member is not eligible
					ret.put("status", "Member is not eligible for this Item");
				}
			}
			else{
				ret.put("status", "Item Not Found");
			}
		}
		return ret;
	}
}
